package com.lhg.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.lhg.framework.influx.InfluxRepository;
import com.lhg.mapper.AlarmMapper;
import com.lhg.pojo.dto.*;
import com.lhg.pojo.entity.Alarm;
import com.lhg.pojo.vo.Pager;
import com.lhg.service.AlarmService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author 刘华桂
 */
@Service
public class AlarmServiceImpl extends ServiceImpl<AlarmMapper, Alarm> implements AlarmService {

    @Autowired
    private InfluxRepository influxRepository;

    @Override
    public Pager<QuotaAllInfo> queryAlarmLog(Long page, Long pageSize, String start, String end, String alarmName, String deviceId) {
        //1.where条件查询语句部分构建

        StringBuilder whereQl=new StringBuilder("where alarm='1' ");
        if(!Strings.isNullOrEmpty(start)){
            whereQl.append("and time>='").append(start).append("' ");
        }
        if(!Strings.isNullOrEmpty(end)){
            whereQl.append("and time<='").append(end).append("' ");
        }
        if(!Strings.isNullOrEmpty(alarmName)){
            whereQl.append("and alarmName=~/").append(alarmName).append("/ ");
        }
        if(!Strings.isNullOrEmpty(deviceId)){
            whereQl.append("and deviceId=~/^").append(deviceId).append("/ ");
        }

        //2.查询记录语句
        StringBuilder listQl=new StringBuilder("select * from quota  ");
        listQl.append(whereQl);
        listQl.append("order by desc limit ").append(pageSize).append(" offset ").append((page - 1) * pageSize);


        //3.查询记录数语句
        StringBuilder countQl=new StringBuilder("select count(value) from quota ");
        countQl.append(whereQl);


        //4.执行查询记录语句
        List<QuotaAllInfo> quotaList = influxRepository.query(listQl.toString(), QuotaAllInfo.class);
        // 添加时间格式处理
        for(QuotaAllInfo quotaAllInfo:quotaList){
            //2020-09-19T09:58:34.926Z   DateTimeFormatter.ISO_OFFSET_DATE_TIME
            //转换为 2020-09-19 09:58:34  格式
            LocalDateTime dateTime = LocalDateTime.parse(quotaAllInfo.getTime(), DateTimeFormatter.ISO_OFFSET_DATE_TIME);
            String time = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"));
            quotaAllInfo.setTime(time);
        }

        //5.执行统计语句
        List<QuotaCount> quotaCount = influxRepository.query(countQl.toString(), QuotaCount.class);

        //6.封装返回结果
        if(quotaCount==null || quotaCount.size()==0){
            Pager<QuotaAllInfo> pager= new Pager<>(0L, 0L);
            pager.setPage(0);
            pager.setItems(Lists.newArrayList());
            return pager;
        }


        // 总记录数
        Long totalCount = quotaCount.get(0).getCount();

        Pager<QuotaAllInfo> pager=new Pager<>(totalCount,pageSize);
        pager.setPage(page);
        pager.setItems(quotaList);

        return pager;
    }

    @Override
    public List<Alarm> getByQuotaId(Integer quotaId) {
        QueryWrapper<Alarm> wrapper = new QueryWrapper<>();
        wrapper
                .lambda()
                .eq(Alarm::getQuotaId,quotaId)
                .orderByDesc(Alarm::getLevel);

        return this.list(wrapper);
    }

    @Override
    public Alarm verifyQuota(QuotaDTO quotaDTO) {
        List<Alarm> alarmList = getByQuotaId(quotaDTO.getId());

        Alarm alarm = null;
        for (Alarm alarmEntity : alarmList) {
            //判断：操作符和指标对比
            if ("String".equals(quotaDTO.getValueType()) || "Boolean".equals(quotaDTO.getValueType())) {
                if ("=".equals(alarmEntity.getOperator()) && quotaDTO.getStringValue().equals(alarmEntity.getThreshold())) {
                    alarm = alarmEntity;
                    break;
                }
            } else //数值
            {
                if (">".equals(alarmEntity.getOperator()) && quotaDTO.getValue() > alarmEntity.getThreshold()) {
                    alarm = alarmEntity;
                    break;
                }
                if ("<".equals(alarmEntity.getOperator()) && quotaDTO.getValue() < alarmEntity.getThreshold()) {
                    alarm = alarmEntity;
                    break;
                }
                if ("=".equals(alarmEntity.getOperator()) && quotaDTO.getValue().equals(alarmEntity.getThreshold() + 0.0)) {
                    alarm = alarmEntity;
                    break;
                }
            }

        }
        return alarm;
    }

    @Override
    public DeviceInfoDTO verifyDeviceInfo(DeviceInfoDTO deviceInfoDTO) {

        // 封装指标的告警  封装设备的告警
        DeviceDTO deviceDTO = deviceInfoDTO.getDevice();

        //假设不告警
        deviceDTO.setLevel(0);
        deviceDTO.setAlarm(false);
        deviceDTO.setAlarmName("正常");
        deviceDTO.setStatus(true);
        deviceDTO.setOnline(true);

        for(QuotaDTO quotaDTO :deviceInfoDTO.getQuotaList() ){

            //根据指标得到告警信息
            Alarm alarm = verifyQuota(quotaDTO);
            //如果指标存在告警
            if(alarm!=null){

                quotaDTO.setAlarm("1");
                //告警名称
                quotaDTO.setAlarmName( alarm.getName() );
                //告警级别
                quotaDTO.setLevel( alarm.getLevel()+"" );
                //告警web钩子
                quotaDTO.setAlarmWebHook(alarm.getWebHook());
                //沉默周期
                quotaDTO.setCycle( alarm.getCycle() );
                //存储设备告警信息
                if(alarm.getLevel() > deviceDTO.getLevel()){
                    deviceDTO.setLevel( alarm.getLevel() );
                    deviceDTO.setAlarm(true);
                    deviceDTO.setAlarmName(alarm.getName());
                }
                //如果指标不存储在告警
            }else{
                quotaDTO.setAlarm("0");
                quotaDTO.setAlarmName("正常");
                quotaDTO.setLevel("0");
                quotaDTO.setAlarmWebHook("");
                quotaDTO.setCycle(0);
            }
        }
        return deviceInfoDTO;
    }

    @Override
    public IPage<Alarm> queryPage(Long page, Long pageSize, String alarmName, Integer quotaId) {
        LambdaQueryWrapper<Alarm> wrapper = new LambdaQueryWrapper<>();
        if(!Strings.isNullOrEmpty(alarmName)){
            wrapper.like(Alarm::getName,alarmName);
        }
        if(quotaId != null){
            wrapper.eq(Alarm::getQuotaId,quotaId);
        }
        wrapper.orderByDesc(Alarm::getId);

        //wrapper.orderByDesc(AlarmEntity::getCreateTime);

        Page<Alarm> pageResult = new Page<>(page,pageSize);

        return this.page(pageResult,wrapper);
    }
}
